import { router } from '@/router/index'
import { useAuth } from '@/stores/auth'
import { useSettings } from '@/stores/settings'
import { getPermissionRoutes } from '@/api/auth'
import { menuRoutes } from '@/router/routes'
import lodash from 'lodash'
import { message } from 'ant-design-vue'
let routes: { name: string; path: string }[] = [] //该路由数组用于给cms菜单赋值

function onFilterFirstLevel(routes: any, routeKeys: string[]): any[] {
  if (Array.isArray(routes)) {
    return routes.filter((route) => {
      return routeKeys.includes(route.name)
    })
  } else {
    return []
  }
}

function onFilterSecondLevel(routes: any[], routeKeys: string[]) {
  return routes.map((route) => {
    if (route.children?.length) {
      route.children = onFilterFirstLevel(route.children, routeKeys)
    }
  })
}

function filterFn(routes: any[], routeKeys: string[]) {
  const first = onFilterFirstLevel(routes, routeKeys)
  if (first.length) {
    onFilterSecondLevel(first, routeKeys)
  }
  return first
}

/**
 * 将接口返回的路由列表转换为router.ts中定义的路由列表
 * @param data
 */
export function handlePermissionRoutes(data: string[]) {
  const routeKeys = lodash.cloneDeep(data)
  const filterRoutes = lodash.cloneDeep(menuRoutes)
  return filterFn(filterRoutes, routeKeys)
}

/**
 * 获取会被keepAlive组件缓存的路由组件
 * obj 为路由树
 */
function extractKeepAliveObjects(obj: any, includeResult = [], excludeResult = []) {
  obj.forEach((item: any) => {
    if (item.meta.keepAlive) {
      includeResult.push(item as never)
    } else {
      excludeResult.push(item as never)
    }
    if (item.children) {
      extractKeepAliveObjects(item.children, includeResult)
    }
  })
  return { includeResult, excludeResult }
}

function setCacheRoutes(routes: any[]) {
  const settingStore = useSettings()
  const include: string[] = []
  const exclude: string[] = []
  routes.forEach((item) => {
    if (item?.meta?.keepAlive) {
      item.name && include.push(item.name)
    } else {
      item.name && exclude.push(item.name)
    }
  })
  settingStore.$patch({
    include: include,
    exclude: exclude
  })
}

/**
 * 获取接口返回路由数组的name
 */
function getAllNames(objList: any[]) {
  let names: any[] = []

  objList?.forEach((item) => {
    names.push(item.name)

    if (item.children && Array.isArray(item.children)) {
      names = names.concat(getAllNames(item.children))
    }
  })

  return names
}

/**
 * 生成对应用户的权限路由
 */
export const dynamicRoutes = async () => {
  const store = useAuth()
  const token = store?.token
  if (!token) return
  const result: any = await getPermissionRoutes()
  const ROUTES = result?.data?.routes
  const _result = getAllNames(ROUTES) //获取接口资源返回的路由树中name的集合
  const filterRoutes = handlePermissionRoutes(_result) //过滤掉routes中无用的route
  if (Array.isArray(filterRoutes) && filterRoutes.length) {
    filterRoutes.forEach((item) => {
      router.addRoute(item)
    })
    routes = lodash.cloneDeep(filterRoutes) //该routes用于生成cms menu
    const flatRoutes = router.getRoutes()
    setCacheRoutes(flatRoutes)
  } else {
    const flatRoutes = router.getRoutes()
    const pathName = window.location.pathname
    const el = flatRoutes.find((item) => item.path === pathName)
    setCacheRoutes(flatRoutes)
    if (el) {
      await router.push({
        name: el.name
      })
    } else {
      await message.error('暂无访问权限！', 1)
      await router.push({
        name: 'NotFound'
      })
    }
  }
}
export { routes }
